package com.javaboy.vhr.controller.system.basicset;

import com.javaboy.vhr.entity.Menu;
import com.javaboy.vhr.entity.Role;
import com.javaboy.vhr.service.MenuService;
import com.javaboy.vhr.service.RoleService;
import com.javaboy.vhr.utils.result.ResultDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: gaoyang
 * @date: 2021-01-25 14:16
 * @description: 权限管理API
 */
@Slf4j
@Api(tags = "权限API")
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissionController {

    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;

    @ApiOperation(value = "获取角色列表")
    @GetMapping("/roles")
    public ResultDTO<List<Role>> getAllRoles() {
        List<Role> list = this.roleService.getAllRoles();
        return ResultDTO.success(list);
    }

    @ApiOperation(value = "获取菜单列表")
    @GetMapping("/menus")
    public ResultDTO<List<Menu>> getAllMenus() {
        List<Menu> list = this.menuService.getAllMenus();
        return ResultDTO.success(list);
    }

    @ApiOperation(value = "获取菜单id列表")
    @GetMapping("/mids")
    public ResultDTO<List<Integer>> getMidsByRid(@RequestParam(name = "rid", required = true) Integer rid) {
        List<Integer> list = this.menuService.getMidsByRid(rid);
        return ResultDTO.success(list);
    }

    @ApiOperation(value = "修改角色权限")
    @PutMapping("/edit")
    public ResultDTO<Void> updateMenuRole(
            @RequestParam(name = "rid", required = true) Integer rid, Integer[] mids) {
        this.menuService.updateMenuRole(rid, mids);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was updated.", Role.class.getSimpleName(), rid);
        }
        return ResultDTO.success("修改成功");
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/role/add")
    public ResultDTO<Role> addRole(@RequestBody Role role) {
        Role insert = this.roleService.insert(role);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was created.", Role.class.getSimpleName(), insert.getId());
        }
        return ResultDTO.success("添加成功", insert);
    }

    @ApiOperation(value = "根据角色id删除角色")
    @DeleteMapping("/role/delete")
    public ResultDTO<Void> deleteRoleById(@RequestParam(name = "rid", required = true) Integer rid) {
        ResultDTO<Void> resultDTO = this.roleService.deleteById(rid);
        if (resultDTO.getStatus()) {
            log.info("{} instance {} was deleted.", Role.class.getSimpleName(), rid);
            return ResultDTO.success(resultDTO.getMsg());
        }
        log.info("{} instance {} fail to delete.", Role.class.getSimpleName(), rid);
        return ResultDTO.error(resultDTO.getMsg());
    }

}
